// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
module.exports = {
	_before: function() { // 通用预处理器

	},

	async getCustomerById(par) {
		const id = par.id
		const db = uniCloud.database();
		const collection = db.collection('sunny-custom');

		const res = await collection.doc(id).get();
		if (res.data.length === 0) {
			return {
				code: 200,
				resultCode: -1,
				data: [],
				message: '没有找到'
			};
		}

		return {
			code: 200,
			resultCode: 0,
			data: res.data[0],
			message: '查询成功'
		}
	},
	// 获取置业顾问的客户
	async getCurZYGWcustomer({
		userId
	}) {
		const db = uniCloud.database();
		const collection = db.collection('sunny-custom');
		const res = await collection.where({
				consultantId: userId,
				isRegistration: 1
			})
			.orderBy('updateTime', 'desc')
			.get();
		return {
			code: 200,
			resultCode: 0,
			data: res.data,
			message: '查询成功'
		}
	},

	async getZYGWcustomer({
		userId,
		pageNo = 1,
		pageSize = 10,
		customerName,
		isRegistration,
		intentionLevel
	}) {
		const db = uniCloud.database();

		try {
			// 使用链式调用构建聚合查询
			let aggregate = db.collection('sunny-custom').aggregate();

			// 匹配阶段
			aggregate.match({
				consultantId: userId
			});

			// 添加可选筛选条件
			if (isRegistration !== undefined && isRegistration !== null && isRegistration !== '') {
				aggregate.match({
					isRegistration: isRegistration
				});
			}

			if (intentionLevel && Array.isArray(intentionLevel) && intentionLevel.length > 0) {
				aggregate.match({
					intentionLevel: db.command.in(intentionLevel)
				});
			}

			if (customerName) {
				aggregate.match({
					customerName: new RegExp(customerName, 'i')
				});
			}

			// 排序阶段
			aggregate.sort({
				updateTime: -1
			});

			// 分页阶段
			const skip = (pageNo - 1) * pageSize;
			aggregate.skip(skip);
			aggregate.limit(pageSize);

			// 执行聚合查询
			const dataRes = await aggregate.end();

			// 获取总数 - 使用普通查询方式
			let countQuery = db.collection('sunny-custom').where({
				consultantId: userId
			});

			if (isRegistration !== undefined && isRegistration !== null && isRegistration !== '') {
				countQuery = countQuery.where({
					isRegistration: isRegistration
				});
			}

			if (intentionLevel && Array.isArray(intentionLevel) && intentionLevel.length > 0) {
				countQuery = countQuery.where({
					intentionLevel: db.command.in(intentionLevel)
				});
			}

			if (customerName) {
				countQuery = countQuery.where({
					customerName: new RegExp(customerName, 'i')
				});
			}

			const countRes = await countQuery.count();
			const total = countRes.total;
			const totalPages = Math.ceil(total / pageSize);

			return {
				code: 200,
				resultCode: 0,
				data: {
					list: dataRes.data,
					pageNo: parseInt(pageNo),
					pageSize: parseInt(pageSize),
					total: total,
					totalPages: totalPages,
					hasNext: pageNo < totalPages,
					hasPrev: pageNo > 1
				},
				message: '查询成功'
			};

		} catch (error) {
			console.error('聚合查询客户列表失败:', error);
			return {
				code: 500,
				resultCode: -1,
				data: null,
				message: '查询失败: ' + error.message
			};
		}
	},
	// 获取中介的客户
	async getZJCustomer() {

	},
	/**
	 * 根据手机号查询客户
	 * @param {string} phone 手机号
	 * @returns {object} 查询结果
	 */
	async getCustomerByPhone({
		phone
	}) {
		const db = uniCloud.database();
		const collection = db.collection('sunny-custom');


		const res = await collection.where({
			phone
		}).get();

		console.log(res)

		if (res.data.length === 0) {
			return {
				code: 200,
				resultCode: 0,
				data: [],
				message: '查询成功'
			};
		}

		return {
			code: 0,
			resultCode: 0,
			data: res.data[0],
			message: '查询成功'
		};
	},

	/**
	 * 分配置业顾问
	 * @param {string} customerId 客户ID
	 * @param {string} consultantId 顾问ID
	 * @param {string} consultantName 顾问姓名
	 * @returns {object} 操作结果
	 */
	async assignConsultant(params) {
		const {
			customerId,
			consultantId,
			consultantName
		} = params
		const db = uniCloud.database();
		const collection = db.collection('sunny-custom');
		const currentData = await collection.doc(customerId).get();
		const currentVisitCount = currentData.data[0].visitCount || 0;
		const updateData = {
			consultantId,
			consultantName,
			isRegistration: 1, // 已分配状态
			updateTime: Date.now(),
			visitTime: Date.now(),
			visitCount: currentVisitCount + 1 // visitCount 自增
		};

		console.log('customerName', updateData)

		const res = await collection.doc(customerId).update(updateData);

		return {
			code: 200,
			data: res,
			resultCode: 0,
			message: '分配成功'
		};
	},

	/**
	 * 添加客户
	 * @param {Object} params 客户信息参数
	 * @param {string} params.customerName 客户姓名
	 * @param {string} params.phone 手机号
	 * @param {string} params.email 邮箱
	 * @param {number} params.sourceType 来源类型
	 * @param {number} params.intentionLevel 意向等级
	 * @param {string} params.notes 备注
	 * @param {string} params.visitTime 到访时间
	 * @param {number} params.status 状态
	 * @param {string} params.gender 性别
	 * @param {number} params.age 年龄
	 * @param {string} params.address 地址
	 * @param {string} params.company 公司
	 * @param {string} params.job 职业
	 * @param {string} params.remark 额外备注
	 * @param {string} params.avatarUrl 头像URL
	 * @param {string} params.weixin 微信
	 * @param {string} params.qq QQ
	 * @param {string} params.birthday 生日
	 * @param {number} params.level 客户级别
	 * @param {string} params.marriage 婚姻状况
	 * @param {string} params.income 收入
	 * @param {string} params.familyStatus 家庭状况
	 * @param {string} params.eventType  [1,2]
	 * @param {string} params.idCard 客户身份证
	 * @returns {object} 添加结果
	 */
	async addCustomer(params) {
		let {
			customerName,
			phone,
			email,
			sourceType,
			intentionLevel,
			notes,
			visitTime,
			status,
			gender,
			age,
			address,
			company,
			job,
			remark,
			avatarUrl,
			weixin,
			qq,
			birthday,
			level,
			marriage,
			income,
			familyStatus,
			eventType,
			typeMap
		} = params;

		const db = uniCloud.database();
		const collection = db.collection('sunny-custom');

		// 检查手机号是否已存在
		const existing = await collection.where({
			phone
		}).get();
		if (existing.data.length > 0) {
			return {
				code: -1,
				message: '该手机号已存在'
			};
		}
		// 前台登记时,visitTime默认为当前时间，前台回访时，visitTime默认为当前时间
		if (eventType === 2) {
			visitTime = Date.now();
		}

		const customerData = {
			customerName,
			phone,
			email,
			sourceType,
			intentionLevel: intentionLevel || 2,
			notes: notes || '',
			visitTime: visitTime,
			status: status || 1,
			gender,
			age,
			address,
			company,
			job,
			remark,
			avatarUrl,
			weixin,
			qq,
			birthday,
			level,
			marriage,
			income,
			familyStatus,
			createTime: Date.now(),
			updateTime: Date.now(),
			typeMap
		};

		const res = await collection.add(customerData);

		return {
			code: 0,
			resultCode: 0,
			data: {
				id: res.id
			},
			message: '客户登记成功'
		};
	}
}